﻿/* Copyright 2011 Teun Duynstee
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using web = System.Web.Profile;
using System.Configuration;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Driver;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.DefaultSerializer;
using System.IO;

namespace MongoAspnetProviders
{
    public class ProfileProvider : web.ProfileProvider
    {
        public ProfileProvider():base()
        {
        }
        public ProfileProvider(IStoreWrapper<Profile> collection)
            : base()
        {
            _collection = collection;
        }
        #region unimplemented
        public override int DeleteInactiveProfiles(web.ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
        {
            throw new NotImplementedException();
        }

        public override int DeleteProfiles(string[] usernames)
        {
            throw new NotImplementedException();
        }

        public override int DeleteProfiles(web.ProfileInfoCollection profiles)
        {
            throw new NotImplementedException();
        }

        public override web.ProfileInfoCollection FindInactiveProfilesByUserName(web.ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override web.ProfileInfoCollection FindProfilesByUserName(web.ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            List<BsonElement> predicates = GetPredicatesForAuthenticationOptions(authenticationOption);
            predicates.Add(new BsonElement("Name", BsonString.Create(usernameToMatch)));

            return GetProfilesForPredicates(predicates, pageIndex, pageSize, out totalRecords);
        }

        public override web.ProfileInfoCollection GetAllInactiveProfiles(web.ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override web.ProfileInfoCollection GetAllProfiles(web.ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords)
        {
            List<BsonElement> predicates = GetPredicatesForAuthenticationOptions(authenticationOption);

            return GetProfilesForPredicates(predicates, pageIndex, pageSize, out totalRecords);
        }

        private static List<BsonElement> GetPredicatesForAuthenticationOptions(web.ProfileAuthenticationOption authenticationOption)
        {
            List<BsonElement> predicates = new List<BsonElement>();
            switch (authenticationOption)
            {
                case System.Web.Profile.ProfileAuthenticationOption.Anonymous:
                    predicates.Add(new BsonElement("IsAuthenticated", BsonBoolean.False));
                    break;
                case System.Web.Profile.ProfileAuthenticationOption.Authenticated:
                    predicates.Add(new BsonElement("IsAuthenticated", BsonBoolean.True));
                    break;
                default:
                    break;
            }
            return predicates;
        }

        private web.ProfileInfoCollection GetProfilesForPredicates(IList<BsonElement> predicates, int pageIndex, int pageSize, out int totalRecords)
        {
            web.ProfileInfoCollection result = new web.ProfileInfoCollection();
            IMongoQuery where = new QueryDocument(
                predicates.ToArray()
                );
            var list = ProfileCollection.Find(where, pageIndex * pageSize, pageSize, out totalRecords);
            foreach (var item in list)
            {
                web.ProfileInfo info = new System.Web.Profile.ProfileInfo(item.Name, true, item.LastUpdated.Value, item.LastUpdated.Value, item.Properties.ToBson().Length);
                result.Add(info);
            }
            return result;
        }

        public override int GetNumberOfInactiveProfiles(web.ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
        {
            throw new NotImplementedException();
        }
        #endregion

        public string ConnectionString { get; protected set; }

        public override string ApplicationName
        {
            get; set;
        }
        static DateTime storage = DateTime.MinValue;
        private IStoreWrapper<Profile> _collection = null;
        protected IStoreWrapper<Profile> ProfileCollection
        {
            get
            {
                if (_collection == null)
                {
                    MongoDatabase db = MongoDatabase.Create(this.ConnectionString);
                    MongoCollection<Profile> collection = db.GetCollection<Profile>("profile");
                    DoCollectionInitialization(collection);
                    _collection = new DefaultStoreWrapper<Profile>(collection);
                }
                return _collection;
            }
        }

        private void DoCollectionInitialization(MongoCollection<Profile> collection)
        {
            //collection.EnsureIndex(""
        }

        public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
        {
            SettingsPropertyValueCollection result = new SettingsPropertyValueCollection();
            IMongoQuery searchMe = FindMe(context);
            Profile found = ProfileCollection.FindOne(searchMe);


            BsonReader reader;
            if (found == null)
            {
                reader = BsonReader.Create(new BsonDocument());
            }
            else
            {
                reader = BsonReader.Create(found.Properties);
            }
            reader.ReadStartDocument();
            BsonReaderBookmark startOfProperties = reader.GetBookmark();
            foreach (SettingsProperty property in collection)
            {
                SettingsPropertyValue value = new SettingsPropertyValue(property);
                if (found != null 
                    && found.Properties.Contains(property.Name) 
                    )
                {
                    reader.ReturnToBookmark(startOfProperties);
                    if (reader.FindElement(property.Name))
                    {
                        value.PropertyValue = BsonSerializer.Deserialize(reader, property.PropertyType);
                    }
                }
                result.Add(value);
            }

            string key = "key";
            MemoryStream ms = new MemoryStream(2000);
            foreach (SettingsPropertyValue setting in result)
            {
                
            }

            return result;
        }

        private static IMongoQuery FindMe(SettingsContext context)
        {
            if (!context.ContainsKey("UserName"))
            {
                throw new ArgumentException("SettingsContext should contain UserName");
            }
            return new QueryDocument(
                new BsonElement("Name", new BsonString((string)context["UserName"]))
                );
        }

        public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
        {
            BsonDocument properties = new BsonDocument();
            foreach (SettingsPropertyValue property in collection)
            {
                AddValueToDocument(properties, property.Name, property.PropertyValue, property.Property.PropertyType);
            }
            IMongoUpdate update = UpdateProfile(context, properties);

            ProfileCollection.Update(FindMe(context), update, UpdateFlags.Upsert);
        }

        private void AddValueToDocument(BsonDocument doc, string name, object value, Type typeOfValue)
        {
            BsonValue mappedValue;
            if (value == null)
            {
                // nop
            //}else if (BsonTypeMapper.TryMapToBsonValue(value, out mappedValue))
            //{
            //    doc.Add(name, mappedValue);
            }
            else
            {
                BsonDocumentWriter writer = new BsonDocumentWriter();
                writer.WriteStartDocument();
                writer.WriteName("value");
                BsonSerializer.Serialize(writer, typeOfValue, value);
                writer.WriteEndDocument();
                doc.Add(name, writer.TopLevelDocument["value"]);
            }
        }


        private IMongoUpdate UpdateProfile(SettingsContext context, BsonDocument properties)
        {
            return new UpdateDocument(
                new BsonElement("Name", BsonValue.Create(context["UserName"])),
                new BsonElement("IsAuthenticated", BsonValue.Create(context["IsAuthenticated"])),
                new BsonElement("LastUpdated", BsonDateTime.Create(DateTime.Now)),
                new BsonElement("LastActivity", BsonDateTime.Create(DateTime.Now)),
                new BsonElement("Properties", properties)
                );
        }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            this.ConnectionString = "";
            foreach (string item in config.Keys)
            {
                if (item.ToLower() == "connectionstring")
                {
                    this.ConnectionString = config[item];
                }
            }
        }
    }
}
